package com.buss.FrontController;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.buss.areainfo.entity.AreaInfoEntity;
import com.buss.areainfo.service.impl.AreaInfoServiceImpl;
import com.buss.artcomments.entity.BnsArticleCommentsEntity;
import com.buss.artcomments.service.BnsArticleCommentsServiceI;
import com.buss.article.entity.BnsArticleEntity;
import com.buss.article.service.BnsArticleServiceI;
import com.buss.articlegroup.entity.ArticleGroupInfoEntity;
import com.buss.photo.entity.BnsAlbumEntity;
import com.buss.photo.service.BnsAlbumServiceI;
import com.buss.shuoshuo.entity.BnsShuoshuoEntity;
import com.buss.shuoshuo.service.BnsShuoshuoServiceI;
import com.buss.user.entity.BnsUserFriendEntity;
import com.buss.user.entity.BnsUsersInfoEntity;
import com.buss.user.service.BnsUserFriendServiceI;
import com.buss.group.entity.BnsGroupClassEntity;
import com.buss.group.entity.BnsGroupEntity;
import com.buss.log.entity.BnsLogEntity;
import com.buss.log.service.BnsLogServiceI;
import com.buss.logclass.entity.BnsLogClassEntity;
import com.buss.logclass.service.BnsLogClassServiceI;
import com.buss.message.entity.BnsMessageEntity;

/**
 * 前台消息控制层
 * @author hlg
 * @Date 2016-09-20
 */
@Scope("prototype")
@Controller
@RequestMapping("/messageController")
public class MessageController extends BaseController {
	private static final Logger logger = Logger.getLogger(MessageController.class);

	private String message;
	
	@Autowired
	private BnsShuoshuoServiceI bnsShuoshuoService;
	@Autowired
	private BnsLogServiceI bnsRizhiService;
	@Autowired
	private BnsArticleCommentsServiceI bnsRzCommentsService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private BnsLogClassServiceI bnsLogClassService;
	@Autowired
	private BnsUserFriendServiceI bnsUserFriendService;
	@Autowired
	private BnsAlbumServiceI bnsAlbumService;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	
	/**
	 * 私人消息页面
	 * @return
	 */
	@RequestMapping(params = "privateMessage")
	public ModelAndView privateMessage(Model model,HttpServletRequest request) {
		String pathStr = "front/message";
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		
		Long dataCount = 0L;
		int pageParam = 1;
		String page = request.getParameter("page");
		if (StringUtil.isEmpty(page)) {
			pageParam = 1;
		} else {
			pageParam = Integer.parseInt(page);
		}
		int mbId = userInfo.getUserId();
		dataCount = systemService.getCountForJdbcParam("select count(1) from bns_message where receive_id='" + mbId + "'", null);
		
		//接受
		String sql1 = "SELECT w.title,w.content,w.message_types,w.create_date,w.create_name,w.create_by,"
				+ "w.receive_id,w.receive_name,a.user_id,a.user_name,a.real_name "
				+ "from bns_message w LEFT JOIN bns_users_info a on w.receive_id = a.user_id where w.receive_id='"
				+ mbId+ "' and message_types='4' and w.states='1'";	//states是否发送(1已发，2未发)
		List<Map<String,Object>> messageList1 = systemService.findForJdbc(sql1, pageParam, 5);
		
		//发送者
		String sql2 = "SELECT w.title,w.content,w.message_types,w.create_date,w.create_name,w.create_by,"
				+ "w.receive_id,w.receive_name,a.user_id,a.user_name,a.real_name "
				+ "from bns_message w LEFT JOIN bns_users_info a on w.receive_id = a.user_id where w.create_by='"
				+ mbId+ "' and message_types='4' and w.states='1'";	//states是否发送(1已发，2未发)
		List<Map<String,Object>> messageList2 = systemService.findForJdbc(sql2, pageParam, 5);
		
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		list.addAll(messageList1);
		list.addAll(messageList2);
		
		int pageCount = 0;
		if (dataCount.intValue() > 0 && dataCount.intValue() % 10 == 0) {
			pageCount = dataCount.intValue() / 10;
		} else {
			pageCount = dataCount.intValue() / 10 + 1;
		}
		model.addAttribute("pageCount", pageCount);
		model.addAttribute("messageList", list);
		model.addAttribute("messageList1", messageList1);
		model.addAttribute("messageList2", messageList2);
		model.addAttribute("backgroundColor", "message");
		return new ModelAndView(pathStr);
	}
	
	/**
	 * 公共消息页面,系统消息
	 * @return
	 */
	@RequestMapping(params = "message")
	public ModelAndView message(Model model,HttpServletRequest request) {
		String pathStr = "front/notice";
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		
		String messageType = request.getParameter("messageType");

		Long dataCount = 0L;
		int pageParam = 1;
		String page = request.getParameter("page");
		if (StringUtil.isEmpty(page)) {
			pageParam = 1;
		} else {
			pageParam = Integer.parseInt(page);
		}
		int mbId = userInfo.getUserId();
		dataCount = systemService.getCountForJdbcParam("select count(1) from bns_message where receive_id='" + mbId + "'", null);
		
		//消息类别：1、短信提醒，2、邮件提醒，3、系统提醒
		String sql = "SELECT * from bns_message w where w.receive_id='"+ mbId+"' and w.states='1' ";	//states是否发送(1已发，2未发)
		if(messageType.equals("3")){	//系统提醒-3
			sql +=  " and message_types in (1,2,3)";
			pathStr = "front/sysRemind";
		}else if(messageType.equals("5")){	//公告消息-5
			sql +=  " and message_types = '5'";
			pathStr = "front/notice";
		}
		
		List<Map<String,Object>> messageList = systemService.findForJdbc(sql, pageParam, 10); 
		int pageCount = 0;
		if (dataCount.intValue() > 0 && dataCount.intValue() % 10 == 0) {
			pageCount = dataCount.intValue() / 10;
		} else {
			pageCount = dataCount.intValue() / 10 + 1;
		}
		model.addAttribute("pageCount", pageCount);
		model.addAttribute("messageList", messageList);
		model.addAttribute("backgroundColor", "message");
		return new ModelAndView(pathStr);
	}
	
	/**
	 * 发送消息页面
	 * @return
	 */
	@RequestMapping(params = "sendMessagePage")
	public ModelAndView sendMessagePage(Model model,HttpServletRequest request) {
		String pathStr = "front/sendMessagePage";
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		int mbId = userInfo.getUserId();
		
		List<BnsUserFriendEntity> userFriendLists = systemService.findByProperty(BnsUserFriendEntity.class, "userId", mbId);
		model.addAttribute("userFriendLists", userFriendLists);
		return new ModelAndView(pathStr);
	}
	
	/**
	 * 发送消息
	 * @return
	 */
	@RequestMapping(params = "sendMessage")
	public ModelAndView sendMessage(Model model,HttpServletRequest request) {
//		String pathStr = "front/sendMessagePage";
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		int mbId = userInfo.getUserId();
		
		String friendIdValues = request.getParameter("friendIdV");	//收件人
		String content = request.getParameter("content");
		
		String[] friendId = friendIdValues.split(",");
		
		BnsMessageEntity myMsg = null;
		for(int i=0;i<friendId.length;i++){
			myMsg = new BnsMessageEntity();
			myMsg.setCreateName(userInfo.getUserName());
			myMsg.setCreateBy(mbId+""); 
			myMsg.setReceiveId(friendId[i]);
			myMsg.setReceiveName(friendId[i]);
			myMsg.setContent(content);
			myMsg.setMessageTypes(4);	//私人消息
			myMsg.setStates("Y");
			myMsg.setIsRead("N");	// Y已读，N未读
			systemService.save(myMsg); 
		}
		String pathStr = "redirect:/messageController.do?privateMessage";	
		return new ModelAndView(pathStr);
	}
	
	/**
	 * 选择朋友跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "chooseFriend")
	public ModelAndView chooseFriend(HttpServletRequest request) {
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		int mbId = userInfo.getUserId();
		ModelAndView mv = new ModelAndView("front/chooseFriend"); 
		String ids = oConvertUtils.getString(request.getParameter("ids"));
		return mv;
	}
	
	/**
	 * 会员朋友显示列表
	 * TODO 会员朋友表需要再加个朋友名字段
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridchooseFriend")
	public void datagridChooseMb(BnsUserFriendEntity bnsUserFriendEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		int mbId = userInfo.getUserId();
		
		CriteriaQuery cq = new CriteriaQuery(BnsUserFriendEntity.class, dataGrid);
		cq.eq("userId", mbId); 
		//cq.addOrder(ordername, ordervalue);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsUserFriendEntity);
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	
	
	/**
	 * 我的帖子页面
	 * @return
	 */
	@RequestMapping(params = "myArticle")
	public ModelAndView myArticle(Model model,HttpServletRequest request) {
		String pathStr = "front/myArticle";
		HttpSession session = request.getSession();
		String userId = "";
		String articleId = "";
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		Long dataCount = 0L;
		int pageParam = 1;
		String page = request.getParameter("page");
		if (StringUtil.isEmpty(page)) {
			pageParam = 1;
		} else {
			pageParam = Integer.parseInt(page);
		}
		dataCount = systemService.getCountForJdbcParam("select count(1) from bns_article_comments w where w.comments_id=' " + userId
				+ "' and w.comments_type='1' and w.create_by != '"+userId+"'", null);
		
		userId = userInfo.getUserId().toString();
		
		String sql0 = "SELECT * from bns_article_comments w where w.create_by='"+userId+"' and w.comments_type='0'";
		List<Map<String,Object>> commentsList0 = systemService.findForJdbc(sql0, pageParam, 10);
		
		String sql = "select b.title,b.id,w.create_by,w.create_name,w.comments_type,w.create_date from bns_article_comments w "
				+ "left join bns_users_info a on a.user_id=w.comments_id "
				+ "left join bns_article b on b.id=w.article_id where "
				+ "comments_id='"+userId+"' and w.comments_type='1' " + " and w.create_by != '"+userId+"' ORDER BY create_date DESC";	
		
		 
		List<Map<String,Object>> commentsList = systemService.findForJdbc(sql, pageParam, 10); 
		int pageCount = 0;
		if (dataCount.intValue() > 0 && dataCount.intValue() % 10 == 0) {
			pageCount = dataCount.intValue() / 10;
		} else {
			pageCount = dataCount.intValue() / 10 + 1;
		}
		model.addAttribute("pageCount", pageCount);
		
		model.addAttribute("commentsList", commentsList);
		model.addAttribute("backgroundColor", "myArticle");
		return new ModelAndView(pathStr);
	}
	
	/**
	 * 我的帖子页面切换
	 * @return
	 */
	@RequestMapping(params = "bbsTabsSwitch")
	public ModelAndView bbsTabsSwitch(Model model,HttpServletRequest request) {
		String pageType = request.getParameter("pageType");
		String path = "";
		if(pageType.equals("remark")){
			path = "front/remark";
		}
		if(pageType.equals("activity")){
			path = "front/activity";
		}
		if(pageType.equals("reward")){
			path = "front/reward";
		}
		if(pageType.equals("goods")){
			path = "front/goods";
		}
		if(pageType.equals("Mentionme")){
			path = "front/Mentionme";
		}
		return new ModelAndView(path);
	}
	
	/**
	 * 坛友互动页面
	 * @return
	 */
	@RequestMapping(params = "bbsInteract")
	public ModelAndView bbsInteract(Model model,HttpServletRequest request) {
		String pathStr = "front/bbsInteract";
		model.addAttribute("backgroundColor", "bbsInteract");
		return new ModelAndView(pathStr);
	}
	
	/**
	 * 系统提醒页面
	 * @return
	 */
	@RequestMapping(params = "sysRemind")
	public ModelAndView sysRemind(Model model,HttpServletRequest request) {
		String pathStr = "front/sysRemind";
		model.addAttribute("backgroundColor", "sysRemind");
		return new ModelAndView(pathStr);
	}
	
	/**
	 * 应用提醒页面
	 * @return
	 */
	@RequestMapping(params = "appRemind")
	public ModelAndView appRemind(Model model,HttpServletRequest request) {
		String pathStr = "front/appRemind";
		model.addAttribute("backgroundColor", "appRemind");
		return new ModelAndView(pathStr);
	}
	
	
}
